package com.prs.crm.dao.fs.impl;

import java.sql.SQLException;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.fs.DetailDao;
import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.domain.fs.BankAccount;
import com.prs.crm.domain.fs.Detail;

public class DetailDaoImpl extends BaseDaoImpl<Detail> implements DetailDao{

	@SuppressWarnings("unchecked")
	@Override
	public Double getSUMIncomeByAccount(final BankAccount bankAccount) {
		// TODO Auto-generated method stub
		return (Double)this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = arg0.createCriteria(Detail.class);
				criteria.add(Restrictions.eq("bankAccount", bankAccount));
				criteria.setProjection(Projections.sum("income"));
				criteria.list();
				Double sum = (Double)criteria.list().get(0);
				if(sum == null) {
					sum = 0.00;
				}
				return sum;
			}
			
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public Double getSUMPayByAccount(final BankAccount bankAccount) {
		// TODO Auto-generated method stub
		return (Double) this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = arg0.createCriteria(Detail.class);
				criteria.add(Restrictions.eq("bankAccount", bankAccount));
				criteria.setProjection(Projections.sum("pay"));
				criteria.list();
				Double sum = (Double)criteria.list().get(0);
				if(sum == null) {
					sum = 0.00;
				}
				return sum;
			}
			
		});
	}
	public void saveOrUpdate(Detail detail){
		
		this.getHibernateTemplate().merge(detail);
	}

}
